import 'dart:convert';
import 'package:convert/convert.dart';

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:freemusic/model/AbstractSong.dart';
import 'package:freemusic/model/KugouSong.dart';

const httpHeaders = {
  'Accept':
      'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
  'Accept-Encoding': 'gzip, deflate, br',
  'Accept-Language': 'zh-CN,zh;q=0.9',
  'Connection': 'keep-alive',
  'Content-Type': 'application/json',
  'Cookie':
      'kg_mid=476cfe9902d83c1e0d493afccfb93379; kg_dfid=2lP7JQ4TTOSN0W1U880ujCuI; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1570780461,1571118626',
  'User-Agent':
      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
};

class KuGouAPI {
  static Future<List<KugouSong>> search(String keyword, int page) async {
    Response response = await Dio().get(
        "http://mobilecdn.kugou.com/api/v3/search/song?format=json&keyword=" +
            keyword +
            "&page=$page&pagesize=10&showtype=1");
    
    KugouSong songs = KugouSong();

    return songs.fromRemoteJosn(jsonDecode(response.data));
  }

  static Future<AbstractSong> getSong(String hash) async {
    // String key = _generateMd5(hash);
    // Response response = await Dio().get("http://trackercdnbj.kugou.com/i/v2/?behavior=play&cmd=23&hash=${hash}&pid=2&appid=1005&key=${key}");
    Dio dio = new Dio();
    dio.options.headers = httpHeaders;
    Response response = await dio.get(
        "https://wwwapi.kugou.com/yy/index.php?r=play/getData&hash=$hash");
    KugouSong info = new KugouSong();
    info.fromRemoteJson(response.data);
    return info;
  }

  static String _generateMd5(String data) {
    var content = Utf8Encoder().convert(data + "kgcloudv2");
    var digest = md5.convert(content);
    return hex.encode(digest.bytes);
  }

  static Future download(String url, String savepath) async {
    Response response = await Dio().download(url, savepath);
    return response;
  }
}
